import {
  View,
  Text,
  Image,
  Swiper,
  SwiperItem,
  Video,
  Button,
} from "@tarojs/components";
import ico_list_cell from "@/assets/image/ico_list_cell.svg";
import ico_list_map from "@/assets/image/ico_list_map.svg";
import ico_list_wei from "@/assets/image/ico_list_wei.svg";
import ico_tishi from "@/assets/image/ico_tishi.svg";
import ico_phone_new from "@/assets/image/ico_phone_new.svg";
import shouchange from "@/assets/image/shouchang.svg";

import "./index.scss";
import { useRouter, useShareAppMessage, useShareTimeline } from "@tarojs/taro";
import { useEffect, useState } from "react";
import {
  addCount,
  collectionStore,
  getQrCode,
  indexGetDetail,
} from "@/services/entities/all";
import {
  formatTime,
  getLevelImage,
  getLevelName,
  makePhoneCall,
  preview,
  redirectToWithParams,
  saveImage,
  switchTab,
  toast,
} from "@/helper/utils";
import { getGlobalData, setGlobalData } from "@/global_data";
import { AtNoticebar } from "taro-ui";
import { routes } from "@/constants/routes";
import Taro from "@tarojs/taro";

const ShopDetail = () => {
  const router = useRouter();
  const { params } = router;
  let { storeId } = params;
  let scene = getGlobalData("scene");
  if (scene && scene.storeId) {
    storeId = scene.storeId;
    setGlobalData("scene", "");
  }
  const userData = getGlobalData("userInfo");
  const { openId } = userData ?? {};

  // 用户未登录则跳转到登陆界面

  const [detail, setDetail] = useState<any>({});
  const [qrCode, setQrCode] = useState<any>();
  const addCounts = (type) => {
    addCount({ storeId, type, openId: userData?.openId });
  };

  const getDetail = () => {
    indexGetDetail({ storeId, openId }).then((res: any) => {
      setDetail({ ...res, viewList: res.viewList?.reverse() ?? [] });
    });
  };

  useEffect(() => {
    if (!userData || !openId) {
      redirectToWithParams(routes.ROUTES_INIT, {
        route: "ROUTES_SHOP_DETAIL",
        action: "redirect",
        storeId: storeId,
      });
      return;
    }
    addCounts(0);
    getDetail();
    getCode();
  }, []);

  useShareAppMessage(() => ({
    title: detail.name,
    path: `/pages/init/index?route=ROUTES_SHOP_DETAIL&action=redirect&storeId=${storeId}`,
  }));

  useShareTimeline(() => ({
    title: detail.name,
    query: `storeId=${storeId}`,
  }));

  const collectStore = () => {
    collectionStore({ storeId, openId }).then((res: any) => {
      toast({ title: res.data });
      getDetail();
    });
  };

  const getCode = () => {
    getQrCode({
      page: "pages/index/shopDetail/index",
      scene: `storeId=${storeId}`,
    }).then((res) => {
      setQrCode("data:image/png;base64," + res);
    });
  };

  return (
    <View className="shop-detail-container bg-page pd-tb-36 border-box">
      <View className="flex-column pd-lr-28 border-box">
        <Text className="fs-44 lh-42 cl-black">{detail.name}</Text>
        <View className="mt-32 dis-flex align-center justify-between">
          <View className="dis-flex align-center">
            <Image src={getLevelImage(detail.level)} className="img-36" />
            <Text className="ml-8 fs-28 lh-32 cl-black">
              {getLevelName(detail.level)}
            </Text>
          </View>
          <View
            className="collect dis-flex align-center justify-between br-8 pd-lr-16 pd-tb-8 border-box"
            onClick={collectStore}
          >
            {!detail.isCollection && (
              <Image src={shouchange} className="img-36" />
            )}
            <Text className="ml-8 fs-28 lh-32 cl-E14848">
              {detail.isCollection ? "取消收藏" : "收藏"}
            </Text>
          </View>
        </View>
      </View>
      <Swiper
        className="mt-16 swiper"
        indicatorColor="#999"
        indicatorActiveColor="#333"
        circular
        indicatorDots
        autoplay
      >
        {detail.operationVideoUrl && (
          <Video
            className="video"
            autoplay={true}
            direction={90}
            src={detail.operationVideoUrl}
          ></Video>
        )}
        {detail.imageUrl?.split(",").map((item) => {
          return (
            <SwiperItem key={item}>
              <Image className="banner-img" src={item} />
            </SwiperItem>
          );
        })}
      </Swiper>
      <View className="width-100">
        <AtNoticebar marquee={true} className="banner-text-bg" speed={50}>
          {detail.viewList
            ?.map(
              (item) =>
                `${item.nickName}（${formatTime(item.viewTime)}）访问了当前店铺`
            )
            .join("，")}
        </AtNoticebar>
      </View>
      <View className="dis-flex align-center justify-evenly pd-tb-24 border-box bg-ffffff">
        <View className="flex-column">
          <View className="dis-flex align-end">
            <Text className="fs-38 lh-46 cl-black">
              {detail.viewCount ?? 0}
            </Text>
            <Text className="ml-8 fs-28 lh-32 cl-black">次</Text>
          </View>
          <Text className="mt-6 fs-28 lh-32 cl-848484">浏览次数</Text>
        </View>
        <View className="flex-column">
          <View className="dis-flex align-end">
            <Text className="fs-38 lh-46 cl-black">
              {detail.contactCount ?? 0}
            </Text>
            <Text className="ml-8 fs-28 lh-32 cl-black">次</Text>
          </View>
          <Text className="mt-6 fs-28 lh-32 cl-848484">联系</Text>
        </View>
      </View>
      <View className="mt-16 dis-flex pd-lr-26 border-box bg-ffffff">
        <View className="flex-1 fs-30 lh-32 cl-848484 pd-tb-24 border-box">
          经营范围：
        </View>
        <View className="flex-3 fs-30 lh-32 cl-black pd-tb-24 border-box">
          {detail.shopScope}
        </View>
      </View>
      <View className="dis-flex mt-16 pd-lr-26 border-box bg-ffffff">
        <View className="flex-1 fs-30 lh-32 cl-848484 pd-tb-24 border-box">
          联系人：
        </View>
        <View className="border-bottom flex-3 fs-30 lh-32 cl-black pd-tb-24 border-box">
          {detail.userName}
        </View>
      </View>
      <View className="dis-flex pd-lr-26 border-box bg-ffffff">
        <View className="flex-1 fs-30 lh-32 cl-848484 pd-tb-24 border-box">
          手机号码：
        </View>
        <View className="border-bottom flex-3 fs-30 lh-32 cl-black pd-tb-24 border-box  dis-flex align-center justify-between">
          <View className="flex-1">
            <Text
              onClick={() => {
                addCounts(1);
                makePhoneCall(detail.phone);
              }}
            >
              {detail.phone}
            </Text>
            {detail.phoneDetail
              ? detail.phoneDetail.split(",").map((phone) => {
                  return (
                    <Text
                      className="ml-8"
                      key={phone}
                      onClick={() => {
                        makePhoneCall(phone);
                      }}
                    >
                      {phone}
                    </Text>
                  );
                })
              : ""}
          </View>
          <Image
            src={ico_phone_new}
            className="img-40 ml-10"
            onClick={() => {
              addCounts(1);
              makePhoneCall(detail.phone);
            }}
          />
        </View>
      </View>
      <View className="dis-flex pd-lr-26 border-box bg-ffffff">
        <View className="flex-1 fs-30 lh-32 cl-848484 pd-tb-24 border-box">
          座机号码：
        </View>
        <View className="border-bottom flex-3 fs-30 lh-32 cl-black pd-tb-24 border-box dis-flex align-center justify-between">
          <Text className="flex-1">{detail.landPhone}</Text>
          <Image
            src={ico_list_cell}
            className="img-40 ml-10"
            onClick={() => {
              makePhoneCall(detail.landPhone);
            }}
          />
        </View>
      </View>
      <View className="dis-flex pd-lr-26 border-box bg-ffffff">
        <View className="flex-1 fs-30 lh-32 cl-848484 pd-tb-24 border-box">
          地址：
        </View>
        <View className="border-bottom flex-3 fs-30 lh-32 cl-black pd-tb-24 border-box dis-flex align-center justify-between">
          <Text className="flex-1">
            {detail.address}
            {detail.addressDetail
              ? `；${detail.addressDetail.split(",").join("；")}`
              : ""}
          </Text>
          <Image src={ico_list_map} className="img-40 ml-10" />
        </View>
      </View>
      {detail.factoryAddress ? (
        <View className="dis-flex pd-lr-26 border-box bg-ffffff">
          <View className="flex-1 fs-30 lh-32 cl-848484 pd-tb-24 border-box">
            工厂地址：
          </View>
          <View className="border-bottom flex-3 fs-30 lh-32 cl-black pd-tb-24 border-box dis-flex align-center justify-between">
            <Text className="flex-1">
              {detail.factoryAddress}
              {detail.otherFactoryAddress
                ? `；${detail.otherFactoryAddress.split(",").join("；")}`
                : ""}
            </Text>
            <Image src={ico_list_map} className="img-40 ml-10" />
          </View>
        </View>
      ) : null}
      <View className="mt-16 dis-flex pd-lr-26 border-box bg-ffffff">
        <View className="flex-1 fs-30 lh-32 cl-848484 pd-tb-24 border-box">
          微信：
        </View>
        <View className="border-bottom flex-3 fs-30 lh-32 cl-black pd-tb-24 border-box dis-flex align-center justify-between">
          <Text className="flex-1">{detail.wxCode}</Text>
          <Text
            className="fs-24 cl-blue ml-12"
            onClick={() => {
              Taro.setClipboardData({
                data: detail.wxCode,
              });
            }}
          >
            复制
          </Text>
          <Image src={ico_list_wei} className="img-40 ml-8" />
        </View>
      </View>
      {detail.operationImageUrl?.split(",").map((item, index) => {
        return (
          <Image
            key={index}
            onClick={() => {
              preview(item, detail.operationImageUrl?.split(","));
            }}
            className="banner-img"
            mode="widthFix"
            src={item}
          />
        );
      })}
      <Image
        onClick={() => {
          preview(qrCode, [qrCode]);
        }}
        className="banner-img pd-36 border-box"
        mode="widthFix"
        src={qrCode}
      />
      <View
        class="fs-42 cl-blue mb-20 flex-center"
        onClick={() => {
          saveImage(qrCode);
        }}
      >
        保存图片
      </View>
      <View className="mt-38 flex-center">
        <Image src={ico_tishi} className="img-46" />
        <Text className="ml-8 fs-32 lh-32 cl-848484">
          温馨提示：联系商家时，请说在老板商圈看到
        </Text>
      </View>
      <View className="phone flex-center pd-lr-20 border-box gap-20">
        <Image
          src={ico_phone_new}
          onClick={() => {
            addCounts(1);
            makePhoneCall(detail.phone);
          }}
          className="img-70"
        ></Image>
        <View className="line"></View>
        <Text
          className="fs-36 fw-600"
          onClick={() => {
            switchTab(routes.ROUTES_INDEX);
          }}
        >
          回到首页
        </Text>
        <View className="line"></View>
        <Button className="button-origin fs-36" openType="share">
          分享
        </Button>
      </View>
    </View>
  );
};

export default ShopDetail;
